<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
class General_Model extends Model 
{
    function General_Model()
    {
        parent::Model();
		umask(0);  //   set quyen cho tat ca cac folder theo nhu thu muc goc
    }
	
    function sendEmail2($emails, $subject, $templateName, $data = array(), $mailType = 'html', $from = null)
    {
        global $CI;
        if (! is_array($emails)) {
            $emails = array($emails);
        }
		
		$this->load->library('email');
		$config['mailtype'] = $mailType;
		$this->email->set_newline("\r\n");
		$this->email->initialize($config);
		//$this->email->from($_POST['email'], $_POST['contact_name']);
		//$this->email->to('tkhau@mwc.vn');
		//$this->email->cc('info@nordanic.dk'); 
		//$this->email->subject('Newsletter from bjornekaelderen website');
        /**
         * Load email template from database
         */
        $result = $this->db->get_where('cvj_template_mail', array('name'=> $templateName, 'enabled'=> 1));
        $result = $result->result_array();
        if (empty($result)) {
            return false;
        }
        $content = $result[0];
        /**
         * Load variables
         */
        extract($data);
        ob_start();
        echo eval ('?>'.$content['content']);
        $content = ob_get_contents();
        @ob_end_clean();
        /**
         * Send mail
         */
        try {
            foreach ($emails as $address){
                $CI->email->clear();
                $CI->email->to($address);
                $from = 'test@bjornekaelderen.dk';
                $CI->email->from($from);
                $CI->email->subject($subject);
                $CI->email->message($content);
                $CI->email->send();
            }
        } catch (Exception $e) {
            //Do nothing
        }
    }

/**********************************  CATEGORY MANAGER  ***********************************/
	function get_all_category($parent_id)
	{
		$category_data = array();
		$sql ="SELECT * FROM category c LEFT JOIN category_description cd ON (c.category_id = cd.category_id) WHERE c.parent_id = " . (int)$parent_id . " ORDER BY c.sort_order, cd.name ASC";
		$query = $this->db->query($sql);
		foreach ($query->result_array() as $result) 
		{
			$category_data[] = array(
				'category_id' => $result['category_id'],
				'name'        => $this->getPath($result['category_id']),
				'info'        => $result['info'],
				'sort_order'  => $result['sort_order'],
				'parent_id' => $result['parent_id'],
				'active'  => $result['active']
			);
		
			$category_data = array_merge($category_data, $this->get_all_category($result['category_id']));
		}	
		return $category_data;
	}
	
	function getPath($category_id) 
	{
		$sql = "SELECT name, parent_id FROM category c LEFT JOIN category_description cd ON (c.category_id = cd.category_id) WHERE c.category_id = " . (int)$category_id . "  ORDER BY c.sort_order, cd.name ASC";
		
		$query = $this->db->query($sql);
		foreach ($query->result_array() as $category_info) 
		{
		  if ($category_info['parent_id']) 
		  {
			  return "&nbsp;---&rsaquo; " . $category_info['name']; // Sports >> Football
		  } 
		  else 
		  {
			  return $category_info['name'];
		  }
		}
	}

//======================= GALLERY ======================
	
	function gallery_manager($totalrow='',$num, $offset)
	{
		
		if($totalrow!='')
		{
			$sql ="SELECT count(*) as result FROM gallery";
			$query = $this->db->query($sql);
			foreach ($query->result() as $row)
				return $row->result;	
		}
		
		else
		{
			$this->db->select('*');
			$this->db->from('gallery');
			$this->db->limit($num, $offset);
			$this->db->order_by("id", "desc");
			$query = $this->db->get();
			return $query;
		}
	}

	function delete_gallery_detail($detail_id)
	{
		
		$this->db->trans_start(); 
		$this->db->delete('gallery', array('id' => $detail_id));
		$this->db->trans_complete();
		// end TRANSACTION			
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}
	function add_gallery_detail($arr)
	{
		$this->db->trans_start(); 

		$this->load->helper(array('form', 'url'));
		$config['upload_path'] = './upload/gallery/';
		$config['allowed_types'] = 'gif|jpg|jpeg';
		$config['max_size']	= '300';
		$config['encrypt_name']	= true;
		$this->load->library('upload', $config);
		
        if ( $this->upload->do_upload())
      	{	
				$datax=$this->upload->data();
       	}
		else
		{
			return 0;
		}		
		
		$image1="userfile1";
		if ($this->upload->do_upload($image1))
      	{	
				$datax2=$this->upload->data();
       	}
		else
		{
			return 0;
		}		
		$this->db->set('small_img',$datax['file_name']);
		$this->db->set('big_img',$datax2['file_name']);
		$this->db->set('title', $arr['title']);
		$this->db->insert('gallery'); 

		$this->db->trans_complete();
		// end TRANSACTION			
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}

	}
//==================  END GALLERY ===============

// ================= MENU MANAGER ===============

	function get_job_category_manager_all($id='')
	{
		$this->db->select('*');
		$this->db->from('cvj_job_category');
		//$this->db->join('support', 'support.id = support_description.support_id');
		$this->db->order_by("ordering", "asc");
		if ($id!='')
		{
			$this->db->where('parent_id',$id);
		}
		else
		{
			$this->db->where('parent_id',NULL);
		}
		$query = $this->db->get();		
		return $query;
	}	


	function add_job_category($arr)
	{
		$this->db->trans_start(); 
		$this->db->set('name',$arr['itemname']);
		$this->db->set('ordering',$arr['sort']);
		if ($arr['id'])
		{
			$this->db->set('parent_id',$arr['id']);
		}
		$this->db->insert('cvj_job_category'); 
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}

	function delete_job_category($id)
	{
		$this->db->trans_start(); 
		$this->db->delete('cvj_job_category', array('job_category_id' => $id));
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}
	
	function update_job_category($arr)
	{
		$this->db->trans_start(); 
		$data = array(
               'name' => $arr['item_update'],
			   'ordering' => $arr['updatesorting']
            );

		$this->db->where('job_category_id',$arr['id']);
		$this->db->update('cvj_job_category', $data); 
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}

// =============   END MENU MANAGER	=============================
	
// =============   FAQ MANAGER	=============================
	function get_faq_manager_all($faq_type)
	{
		$this->db->select('*');
		$this->db->from('faq_description');
		$this->db->where('faq_id',$faq_type); // 2 FAQ
		$this->db->order_by("sorting", "desc");
		$query = $this->db->get();
		return $query;
	}
	function add_faq_item($data,$faq_type)
	{
		$this->db->trans_start(); 
		$this->db->set('question',$data['question']);
		$this->db->set('answer',$data['answer']);
		$this->db->set('sorting',$data['sorting']);
		$this->db->set('faq_id',$faq_type);
		$this->db->insert('faq_description'); 
		
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}
	
	function delete_faq($id)
	{
		$this->db->trans_start(); 
		$this->db->delete('faq_description', array('id' => $id));
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}
	
	function get_faq_detail($id)
	{
		$this->db->select('*');
		$this->db->from('faq');
		$this->db->order_by("ordering", "desc");
		$this->db->where('faq_id',$id);
		$query = $this->db->get();
		return $query;
	}
	
	function update_faq_item($arr)
	{
		$this->db->trans_start(); 
		$data = array(
               'question' => $arr['question'],
			   'answer' => $arr['answer'],
               'sorting' => $arr['sorting']
            );

		$this->db->where('id',$arr['id']);
		$this->db->update('faq_description', $data);
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
		
	}
// =============   END FAQ MANAGER	=============================
	
	function get_information($id='')
	{
		$this->db->select('*');
		$this->db->from('information_description');
		$this->db->where('information_id',$id);

		$query = $this->db->get();
		return $query;
	}


	function update_history($arr)
	{
		$this->db->trans_start(); 
		$data = array(
			   'description' => $arr['content']
            );

		$this->db->where('information_id',$arr['id']);
		$this->db->update('information_description', $data);
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}
// ============= ARRTICLE MANAGER ====================================
	function get_all_article($type,$num, $offset)
	{
		$this->db->limit($num, $offset);
		$this->db->select('*');
		$this->db->from('article_description');
		$this->db->where('article_id',$type);
		$this->db->order_by("sorting", "desc");
		$query = $this->db->get();		
		return $query;
	}
	function get_totalrow_article($type)
	{
		$this->db->from('article_description');
		$this->db->where('article_id',$type);
		return $this->db->count_all_results();
	}	
	
	function get_article_detail($id)
	{
		$this->db->select('*');
		$this->db->from('article_description');
		$this->db->where('id',$id);
		$query = $this->db->get();		
		return $query;
	}
	function add_article($type,$arr)
	{
		$this->db->trans_start(); 
		$this->load->helper(array('form', 'url'));
		
		$config['upload_path'] = './upload/sogjob/';
		$config['allowed_types'] = 'gif|jpg|jpeg|png';
		$config['max_size']	= '500';
		$config['encrypt_name']	=TRUE;    // rename to random string
		
		$this->load->library('upload', $config);
			
		if (!empty($_FILES['userfile']['name']))
		{
			if ( $this->upload->do_upload())
			{	
					$datax=$this->upload->data();
					$this->db->set('image',$datax['file_name']);
			}
		}
		$data = array(
			'title' => $arr['title'],
			'small_text' => $arr['short_desc'],
			'sorting' => $arr['sorting'],
               'content' => $arr['maincontent']
            );
		$this->db->set('article_id',$type);
		$this->db->insert('article_description', $data); 
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}

	}
	function update_article($arr)
	{
		$this->db->trans_start(); 
		$this->load->helper(array('form', 'url'));
		
		$config['upload_path'] = './upload/sogjob/';
		$config['allowed_types'] = 'gif|jpg|jpeg|png';
		$config['max_size']	= '500';
		$config['encrypt_name']	=TRUE;    // rename to random string
		
		$this->load->library('upload', $config);
			
		if (!empty($_FILES['userfile']['name']))
		{

			if ( $this->upload->do_upload())
			{	
					$datax=$this->upload->data();
					$this->db->set('image',$datax['file_name']);
					//var_dump($datax);
					
			}
		}
		$data = array(
			'title' => $arr['title'],
			'small_text' => $arr['short_desc'],
			'sorting' => $arr['sorting'],
            'content' => $arr['maincontent']
            );

		$this->db->where('id',$arr['id']);
		$this->db->update('article_description', $data); 
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}
	
	function delete_search_job($id)
	{
		
		$this->db->trans_start(); 
		$this->db->delete('article_description', array('id' => $id));
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}


// ================  END ARTICLE ===============================

// ================  NEWSLETTER MANAGER======================================
	function get_newsletter($totalrow='',$num='', $offset='')
	{

		//$iscompany=$type;
		if ($totalrow=="totalrow")
		{
			
			$sql ="SELECT count(*) as result FROM newsletter";
			$query = $this->db->query($sql);
			foreach ($query->result() as $row)
				return $row->result;
		}
		else
		{
				$this->db->select("*");
				$this->db->from('newsletter');
				$this->db->limit($num, $offset);
				$this->db->order_by("register_date", "desc");
			//$this->db->where("(video!='NULL' or image!='NULL')");
			$query = $this->db->get();
			return $query;
		}

	}

	function sendmail_newsletter($arr)
	{
		
		$this->db->trans_start(); 
		
		$info=$this->get_newsletter_email();
		$subject="Nyhedsbrev fra bjornekaelderen.dk";
		for($i=0;$i<count($info);$i++)
		{	
			
			$infomation=$arr['answer']; //"<p><h3>Click <a href='".base_url().'unsubscribe/'.md5($info[$i]['newsletter_id'])."'>here</a> to unsubscribe from future emails like this</h3></p>";

			$this->sendEmail2($info[$i]['email'], $subject,'sendmail_newsletter', array('infomation' => $infomation),'html');
		}
		
		$this->sendEmail2('tkhau@mwc.vn', $subject,'sendmail_newsletter', array('infomation' => $arr['answer']),'html');
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	
	}
	function get_newsletter_email()
	{

			$this->db->select("*");
			$this->db->from('newsletter');
			$query = $this->db->get();
			$emails=array();
			if($query->num_rows()>0)
			{
				$emails=$query->result_array();
			}
			return $emails;

	}

	function delete_newsletter($id)
	{
		
		$this->db->trans_start(); 
		$this->db->delete('newsletter', array('id' => $id));
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}

// ============= END NEWSLETTER ============
	public function getRandomCode($length = 8) 
    {
        /**
         * @TODO Load lenght of active code from config
         */
        /**
         * String with 62 letters
         */
        $chars      = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $activeCode = '';
        for ($i = 1; $i <= $length; $i++) {
            $activeCode .= $chars{rand(0, 61)};
        }
        return $activeCode;
    }
// ===== SLIDESHOW -- GALLERY================================

	function get_slideshow()
	{
		$this->db->select('*');
		$this->db->from('slideshow');
		$this->db->order_by("id", "desc");
		$query = $this->db->get();		
		return $query;
	}	
	function add_slideshow($arr)
	{
		$this->db->trans_start(); 
		$this->load->helper(array('form', 'url'));
		
		$config['upload_path'] = './upload/slide/';
		$config['allowed_types'] = 'gif|jpg|jpeg|png';
		$config['max_size']	= '500';
		$config['encrypt_name']	=TRUE;    // rename to random string
		
		$this->load->library('upload', $config);
			
		if (!empty($_FILES['userfile']['name']))
		{
			if ( $this->upload->do_upload())
			{	
					$datax=$this->upload->data();
					$this->db->set('image',$datax['file_name']);
			}
		}
		$this->db->insert('slideshow'); 
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}
	function delete_slideshow($id)
	{
		// begin TRANSACTION
		$this->db->trans_start(); 
		
		$this->db->delete('slideshow', array('id' => $id)); 
		$this->db->trans_complete();
		// end TRANSACTION			
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}	
	
	
	function get_totalrow_gallery()
	{
		$this->db->from('gallery');
		return $this->db->count_all_results();
	}
	
	function get_gallery($num, $offset)
	{		
		$this->db->limit($num, $offset);
		$this->db->select('*');
		$this->db->from('gallery');
		$this->db->order_by("id", "desc");
		$query = $this->db->get();		
		return $query;
	}
	function add_gallery($arr)
	{
		$this->db->trans_start(); 
		$this->load->helper(array('form', 'url'));
		
		$config['upload_path'] = './upload/gallery/';
		$config['allowed_types'] = 'gif|jpg|jpeg|png';
		$config['max_size']	= '500';
		$config['encrypt_name']	=TRUE;    // rename to random string
		
		$this->load->library('upload', $config);
			
		if (!empty($_FILES['userfile']['name']))
		{
			if ( $this->upload->do_upload())
			{	
					$datax=$this->upload->data();
					$this->db->set('big_img',$datax['file_name']);
			}
		}
		$this->db->insert('gallery'); 
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}
	function delete_gallery($id)
	{
		// begin TRANSACTION
		$this->db->trans_start(); 
		
		$this->db->delete('gallery', array('id' => $id)); 
		$this->db->trans_complete();
		// end TRANSACTION			
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}	
// ====================== MENU MANAGER ============================	

	function get_menu_manager($id='')
	{
		$this->db->select('*');
		if ($id!='')
		{
			$this->db->from('product');
			$this->db->where('category_id',$id);
			$this->db->order_by("sorting", "desc");
		}
		else
		{
			$this->db->from('category');
			$this->db->order_by("ordering", "desc");

		}
		$query = $this->db->get();		
		return $query;
	}	
	
	function addnew_menu($arr)
	{
		$this->db->trans_start();
		if ($arr['id']!='')
		{
			$this->db->set('name',$arr['itemname']);
			$this->db->set('price',$arr['price']);
			$this->db->set('sorting',$arr['sort']);
			$this->db->set('category_id',$arr['id']);
			$this->db->insert('product'); 
		}
		else
		{
			$this->db->set('name',$arr['itemname']);
			$this->db->set('ordering',$arr['sort']);
			$this->db->set('type',1);
			$this->db->insert('category'); 
		} 
		
		
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}
	function delete_menu($id,$category_id='')
	{
		$this->db->trans_start(); 

		if ($category_id>0)
		{		
			$this->db->delete('product', array('product_id' => $id)); 
		}
		else
		{		
			$this->db->delete('category', array('category_id' => $id)); 
		}
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}
	function get_edit_menu_detail($id,$category='')
	{
		$this->db->select('*');
		if ($category!='')
		{
			$this->db->from('product');
			$this->db->where('product_id',$id);
		}
		else
		{
			$this->db->from('category');
			$this->db->where('category_id',$id);

		}
		$query = $this->db->get();		
		return $query;
	}
	
	function update_menu($arr)
	{
		$this->db->trans_start();
		if ($arr['is_category']!='')
		{
			$this->db->set('name',$arr['item_update']);
			$this->db->set('price',$arr['updateprice']);
			$this->db->set('sorting',$arr['updatesorting']);
			$this->db->where('product_id',$arr['update_id']);
			$this->db->update('product'); 
		}
		else
		{
			$this->db->set('name',$arr['item_update']);
			$this->db->set('ordering',$arr['updatesorting']);
			$this->db->where('category_id',$arr['update_id']);
			$this->db->update('category'); 
		} 
		
		
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}
// ==============  RESERVATION MANAGER ======================	

	function get_reservations($totalrow,$_type='',$_keyword='',$num, $offset)
	{
		if ($totalrow=="totalrow")
		{
			
			$mytype='';
			$type='';
			if ($_type==0)
			{
				$type=" where ((email LIKE '%".$_keyword."%' ) OR (concat(first_name,' ',surname) LIKE '%".$_keyword."%' )  OR (date LIKE '%".$_keyword."%' ) OR (mobile LIKE '%".$_keyword."%' ) OR (comment LIKE '%".$_keyword."%' ))";
			}
			if ($_type==1)
			{
				$type=" and ((email LIKE '%".$_keyword."%' ) OR (concat(first_name,' ',surname) LIKE '%".$_keyword."%' )  OR (date LIKE '%".$_keyword."%' ) OR (mobile LIKE '%".$_keyword."%' ) OR (comment LIKE '%".$_keyword."%' ))";
				$mytype=" where status=0";
			}
			if ($_type==2)
			{
				$type=" and ((email LIKE '%".$_keyword."%' ) OR (concat(first_name,' ',surname) LIKE '%".$_keyword."%' )  OR (date LIKE '%".$_keyword."%' ) OR (mobile LIKE '%".$_keyword."%' ) OR (comment LIKE '%".$_keyword."%' ))";
				$mytype=" where status=1";
			}
			if ($_type==3)
			{
				$type=" and ((email LIKE '%".$_keyword."%' ) OR (concat(first_name,' ',surname) LIKE '%".$_keyword."%' ) OR (date LIKE '%".$_keyword."%' ) OR (mobile LIKE '%".$_keyword."%' ) OR (comment LIKE '%".$_keyword."%' ))";
				$mytype=" where status=2";
			}
			if($_keyword!='')
			{
				$mytype.=$type;
			}

			$sql ="SELECT count(*) as result FROM orders ".$mytype;
			$query = $this->db->query($sql);
			foreach ($query->result() as $row)
				return $row->result;
		}
		else
		{
				$this->db->select("*");
				$this->db->from('orders');
				$this->db->limit($num, $offset);
				//$this->db->order_by("register_date", "desc");
				
				  if ($_type==0)
				  {
					  $this->db->where("((email LIKE '%".$_keyword."%' ) OR (concat(first_name,' ',surname) LIKE '%".$_keyword."%' ) OR (date LIKE '%".$_keyword."%' ) OR (mobile LIKE '%".$_keyword."%' ) OR (comment LIKE '%".$_keyword."%' ))");
				  }
				  if ($_type==1)
				  {
					  $clause="(status=0) and ((email LIKE '%".$_keyword."%' ) OR (concat(first_name,' ',surname) LIKE '%".$_keyword."%' ) OR (date LIKE '%".$_keyword."%' ) OR (mobile LIKE '%".$_keyword."%' ) OR (comment LIKE '%".$_keyword."%' ))";
						$this->db->where($clause);
					  
				  }
				  if ($_type==2)
				  {
						
						$clause="(status=1) and ((email LIKE '%".$_keyword."%' ) OR (concat(first_name,' ',surname) LIKE '%".$_keyword."%' ) OR (date LIKE '%".$_keyword."%' ) OR (mobile LIKE '%".$_keyword."%' ) OR (comment LIKE '%".$_keyword."%' ))";
						$this->db->where($clause);
				  }
				  if ($_type==3)
				  {
					$clause="(status=2) and ((email LIKE '%".$_keyword."%' ) OR (concat(first_name,' ',surname) LIKE '%".$_keyword."%' ) OR (date LIKE '%".$_keyword."%' ) OR (mobile LIKE '%".$_keyword."%' ) OR (comment LIKE '%".$_keyword."%' ))";
						$this->db->where($clause);
					  
				  }
			//$this->db->where("(video!='NULL' or image!='NULL')");
			$this->db->order_by('order_id','desc');
			$query = $this->db->get();
			return $query;
		}
	}
	
	function delete_reserve($id)
	{
	// begin TRANSACTION
		$this->db->trans_start(); 
		
		$this->db->delete('orders', array('order_id' => $id)); 
		$this->db->trans_complete();
		// end TRANSACTION			
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}
	function update_status_reserve($arr)
	{
		$this->db->trans_start();
			$this->db->set('status',$arr['status_option']);
			$this->db->where('order_id',$arr['update_id']);
			$this->db->update('orders'); 
		$this->db->trans_complete();
		if ($this->db->trans_status() == FALSE)
		{
			return 0;
		} 
		else
		{
			return 1;
		}
	}

}
